package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.pojo.Category;
import com.itheima.service.CategoryService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/category")
@Api(tags = "分类相关接口")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;



    @GetMapping("/list")
    public R listCategory(Integer type){//type  null
        // 调用业务层，查询数据 SELECT * FROM category WHERE TYPE = 2
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper();
        qw.eq(type!=null,Category::getType,type);
        List<Category> list = categoryService.list(qw);

        return R.success(list);
    }


    @PutMapping
    public R<String> updateCategory(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    @DeleteMapping
    public R<String> deleteCategory(Long id){
        categoryService.remove(id);
        return R.success("删除分类成功！");
    }

    @PostMapping
    public R<String> addCategory(@RequestBody Category category){
        boolean save = categoryService.save(category);
        return save?R.success("保存分类成功"):R.error("保存分类失败");
    }


    @GetMapping("/page")
    public R queryPage(Integer page,Integer pageSize){
        IPage<Category> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        //排序
        qw.orderByDesc(Category::getSort);
        categoryService.page(pageInfo,qw);
        return R.success(pageInfo);
    }
}
